///
/// 优雅的键盘组件，支持数字键盘、身份证键盘和自定义键盘

import 'package:flutter/material.dart';
import '../../core/elegance_theme.dart';
import '../../core/elegance_base.dart';

/// 键盘类型枚举
enum EKeyboardType {
  /// 数字键盘
  number,
  
  /// 身份证键盘
  idcard,
  
  /// 自定义键盘
  custom,
}

/// 键盘按键类型枚举
enum EKeyType {
  /// 数字键
  number,
  
  /// 字母键
  letter,
  
  /// 特殊字符键
  special,
  
  /// 删除键
  delete,
  
  /// 完成键
  complete,
  
  /// 清空键
  clear,
}

/// 键盘按键数据类
class EKey {
  /// 创建一个键盘按键
  const EKey({
    required this.label,
    this.value,
    required this.type,
    this.widthFactor = 1.0,
    this.heightFactor = 1.0,
  });

  /// 按键显示文本
  final String label;
  
  /// 按键实际值
  final String? value;
  
  /// 按键类型
  final EKeyType type;
  
  /// 宽度系数
  final double widthFactor;
  
  /// 高度系数
  final double heightFactor;
}

/// 键盘事件回调
typedef EKeyboardCallback = void Function(String value, EKeyType type);

/// EKeyboard控件
class EKeyboard extends EleganceStatefulWidget {
  /// 创建EKeyboard控件
  const EKeyboard({
    super.key,
    this.type = EKeyboardType.number,
    this.customKeys,
    this.showDeleteKey = true,
    this.showCompleteKey = true,
    this.showClearKey = false,
    this.randomKeys = false,
    this.maxLength = 20,
    this.onKeyTap,
    this.onComplete,
    this.onDelete,
    this.onClear,
    this.onClose,
    this.backgroundColor,
    this.keyColor,
    this.keyTextColor,
    this.keyHighlightColor,
    this.keyRadius,
    this.keyBorderRadius,
    this.keyBorderColor,
    this.keyBorderWidth,
    this.deleteIcon,
    this.completeText = '完成',
    this.clearText = '清空',
    this.closeText = '关闭',
    this.height = 260,
  });

  /// 键盘类型
  final EKeyboardType type;
  
  /// 自定义按键列表（仅当type为custom时有效）
  final List<EKey>? customKeys;
  
  /// 是否显示删除键
  final bool showDeleteKey;
  
  /// 是否显示完成键
  final bool showCompleteKey;
  
  /// 是否显示清空键
  final bool showClearKey;
  
  /// 是否随机排列按键
  final bool randomKeys;
  
  /// 最大输入长度
  final int maxLength;
  
  /// 按键点击回调
  final EKeyboardCallback? onKeyTap;
  
  /// 完成回调
  final VoidCallback? onComplete;
  
  /// 删除回调
  final VoidCallback? onDelete;
  
  /// 清空回调
  final VoidCallback? onClear;
  
  /// 关闭回调
  final VoidCallback? onClose;
  
  /// 背景颜色
  final Color? backgroundColor;
  
  /// 按键颜色
  final Color? keyColor;
  
  /// 按键文字颜色
  final Color? keyTextColor;
  
  /// 按键高亮颜色
  final Color? keyHighlightColor;
  
  /// 按键圆角
  final double? keyRadius;
  
  /// 按键边框圆角
  final double? keyBorderRadius;
  
  /// 按键边框颜色
  final Color? keyBorderColor;
  
  /// 按键边框宽度
  final double? keyBorderWidth;
  
  /// 删除图标
  final IconData? deleteIcon;
  
  /// 完成按钮文字
  final String completeText;
  
  /// 清空按钮文字
  final String clearText;
  
  /// 关闭按钮文字
  final String closeText;
  
  /// 键盘高度
  final double height;

  @override
  EKeyboardState createState() => EKeyboardState();
}

class EKeyboardState extends EleganceState<EKeyboard> with ThemedMixin {
  /// 数字键盘按键
  final List<EKey> _numberKeys = const [
    EKey(label: '1', value: '1', type: EKeyType.number),
    EKey(label: '2', value: '2', type: EKeyType.number),
    EKey(label: '3', value: '3', type: EKeyType.number),
    EKey(label: '4', value: '4', type: EKeyType.number),
    EKey(label: '5', value: '5', type: EKeyType.number),
    EKey(label: '6', value: '6', type: EKeyType.number),
    EKey(label: '7', value: '7', type: EKeyType.number),
    EKey(label: '8', value: '8', type: EKeyType.number),
    EKey(label: '9', value: '9', type: EKeyType.number),
    EKey(label: '清空', value: 'clear', type: EKeyType.clear),
    EKey(label: '0', value: '0', type: EKeyType.number),
    EKey(label: '删除', value: 'delete', type: EKeyType.delete),
  ];

  /// 身份证键盘按键
  final List<EKey> _idCardKeys = const [
    EKey(label: '1', value: '1', type: EKeyType.number),
    EKey(label: '2', value: '2', type: EKeyType.number),
    EKey(label: '3', value: '3', type: EKeyType.number),
    EKey(label: '4', value: '4', type: EKeyType.number),
    EKey(label: '5', value: '5', type: EKeyType.number),
    EKey(label: '6', value: '6', type: EKeyType.number),
    EKey(label: '7', value: '7', type: EKeyType.number),
    EKey(label: '8', value: '8', type: EKeyType.number),
    EKey(label: '9', value: '9', type: EKeyType.number),
    EKey(label: 'X', value: 'X', type: EKeyType.special),
    EKey(label: '0', value: '0', type: EKeyType.number),
    EKey(label: '删除', value: 'delete', type: EKeyType.delete),
  ];

  /// 获取当前键盘的按键列表
  List<EKey> get _keys {
    List<EKey> keys;
    
    switch (widget.type) {
      case EKeyboardType.number:
        keys = _numberKeys;
        break;
      case EKeyboardType.idcard:
        keys = _idCardKeys;
        break;
      case EKeyboardType.custom:
        keys = widget.customKeys ?? [];
        break;
    }

    // 处理特殊按键的显示逻辑
    if (widget.type != EKeyboardType.custom) {
      keys = keys.map((key) {
        if (key.type == EKeyType.delete && !widget.showDeleteKey) {
          return EKey(label: '', value: '', type: EKeyType.special, widthFactor: 0);
        }
        if (key.type == EKeyType.clear && !widget.showClearKey) {
          return EKey(label: '', value: '', type: EKeyType.special, widthFactor: 0);
        }
        return key;
      }).toList();
    }

    // 过滤掉宽度为0的按键
    keys = keys.where((key) => key.widthFactor > 0).toList();

    // 随机排列按键
    if (widget.randomKeys) {
      final List<EKey> randomKeys = [...keys];
      final List<EKey> specialKeys = randomKeys.where((key) => 
        key.type == EKeyType.delete || 
        key.type == EKeyType.complete || 
        key.type == EKeyType.clear
      ).toList();
      
      final List<EKey> normalKeys = randomKeys.where((key) => 
        key.type == EKeyType.number || 
        key.type == EKeyType.letter || 
        key.type == EKeyType.special
      ).toList();
      
      // 随机排序普通按键
      normalKeys.shuffle();
      
      // 重新组合按键列表
      keys = [];
      int normalIndex = 0;
      
      for (final key in randomKeys) {
        if (key.type == EKeyType.delete || 
            key.type == EKeyType.complete || 
            key.type == EKeyType.clear) {
          keys.add(key);
        } else if (normalIndex < normalKeys.length) {
          keys.add(normalKeys[normalIndex]);
          normalIndex++;
        }
      }
    }

    return keys;
  }

  /// 处理按键点击
  void _onKeyTap(EKey key) {
    // 调用通用回调
    widget.onKeyTap?.call(key.value ?? '', key.type);
    
    // 调用特定回调
    switch (key.type) {
      case EKeyType.delete:
        widget.onDelete?.call();
        break;
      case EKeyType.complete:
        widget.onComplete?.call();
        break;
      case EKeyType.clear:
        widget.onClear?.call();
        break;
      default:
        break;
    }
  }

  /// 构建按键
  Widget _buildKey(EKey key) {
    final keyColor = widget.keyColor ?? theme.surfaceColor;
    final keyTextColor = widget.keyTextColor ?? theme.textPrimaryColor;
    final keyHighlightColor = widget.keyHighlightColor ?? theme.primaryLight;
    final keyRadius = widget.keyRadius ?? theme.borderRadius;
    final keyBorderColor = widget.keyBorderColor ?? theme.borderColor;
    final keyBorderWidth = widget.keyBorderWidth ?? theme.borderWidth;

    return Expanded(
      flex: (key.widthFactor * 10).toInt(),
      child: GestureDetector(
        onTapDown: (details) {
          _onKeyTap(key);
        },
        child: Container(
          margin: const EdgeInsets.all(4),
          padding: EdgeInsets.symmetric(vertical: widget.height / 10 * key.heightFactor),
          decoration: BoxDecoration(
            color: keyColor,
            borderRadius: BorderRadius.circular(keyRadius),
            border: Border.all(
              color: keyBorderColor,
              width: keyBorderWidth,
            ),
          ),
          child: Center(
            child: key.type == EKeyType.delete && widget.deleteIcon != null
                ? Icon(
                    widget.deleteIcon,
                    color: keyTextColor,
                    size: 20,
                  )
                : Text(
                    key.label,
                    style: TextStyle(
                      color: keyTextColor,
                      fontSize: 18,
                      fontWeight: FontWeight.normal,
                    ),
                  ),
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final backgroundColor = widget.backgroundColor ?? theme.backgroundColor;
    final rowCount = widget.type == EKeyboardType.custom ? 
        ((_keys.length + 2) / 3).ceil() : 4;

    // 构建键盘行
    final List<Widget> rows = [];
    int keyIndex = 0;
    
    for (int i = 0; i < rowCount; i++) {
      final List<EKey> rowKeys = [];
      int columnCount = 3;
      
      // 最后一行可能有特殊布局
      if (i == rowCount - 1 && widget.type != EKeyboardType.custom) {
        columnCount = widget.showClearKey ? 3 : 2;
      }
      
      for (int j = 0; j < columnCount && keyIndex < _keys.length; j++) {
        rowKeys.add(_keys[keyIndex]);
        keyIndex++;
      }
      
      if (rowKeys.isNotEmpty) {
        rows.add(
          Row(
            children: rowKeys.map(_buildKey).toList(),
          ),
        );
      }
    }

    // 如果显示完成键，添加到最后一行
    if (widget.showCompleteKey && widget.type != EKeyboardType.custom) {
      rows.add(
        Row(
          children: [
            Expanded(
              child: GestureDetector(
                onTap: () {
                  _onKeyTap(EKey(label: widget.completeText, value: 'complete', type: EKeyType.complete));
                },
                child: Container(
                  margin: const EdgeInsets.all(4),
                  padding: EdgeInsets.symmetric(vertical: widget.height / 10),
                  decoration: BoxDecoration(
                    color: theme.primaryColor,
                    borderRadius: BorderRadius.circular(widget.keyRadius ?? theme.borderRadius),
                  ),
                  child: Center(
                    child: Text(
                      widget.completeText,
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      );
    }

    return Container(
      height: widget.height + (widget.showCompleteKey ? widget.height / 10 : 0),
      decoration: BoxDecoration(
        color: backgroundColor,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 10,
            offset: const Offset(0, -5),
          ),
        ],
      ),
      child: Column(
        children: rows,
      ),
    );
  }
}